const Koa = require("koa");
const Router = require("koa-router");
const cors = require("@koa/cors");
const KoaStatic = require("koa-static");
const { koaBody } = require("koa-body");
const app = new Koa();
const router = new Router();
const path = require("path");
const { baseURL } = require("./config");

app.use(cors());
app.use(KoaStatic(path.resolve(__dirname, "uploads")));
app.use(
  koaBody({
    multipart: true,
    formidable: {
      keepExtensions: true, // 保持文件的后缀
      uploadDir: path.resolve(__dirname, "uploads"), // 设置文件上传的目录
    },
  })
);

router.get("/api/test", async (ctx, next) => {
  ctx.body = {
    code: 0,
    msg: "请求成功",
    data: {
      list: [1, 2, 3],
    },
  };
});
// http://127.0.0.1:3000/612af48ebe72ddab2e75c4300.jpg
router.post("/api/upload", async (ctx, next) => {
  console.log(ctx.request.files);
  ctx.body = {
    code: 0,
    msg: "请求成功",
    data: {
      files: ctx.request.files.avatar,
      src: `${baseURL}/${ctx.request.files.avatar.newFilename}`,
    },
  };
});

app.use(router.routes());

app.listen(3000, () => {
  console.log("Server is running on http://localhost:3000");
});
